package com.iemes.controller.device;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iemes.annotation.SystemLog;
import com.iemes.controller.base.ConstantController;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.*;
import com.iemes.mapper.DeviceFaultDetailMapper;
import com.iemes.mapper.DeviceMapper;
import com.iemes.mapper.UserMapper;
import com.iemes.util.Common;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/devicefault/")
public class DeviceFaultController extends BaseController {

    @Inject
    private UserMapper userMapper;

    @Inject
    private DeviceMapper deviceMapper;

    @Inject
    private DeviceFaultDetailMapper deviceFaultDetailMapper;


    @RequestMapping("devicefault")
    public String listUI(Model model) throws Exception {
        String [] btnArray = new String[]{"<button type=\"button\" id=\"addAccount\" class=\"btn btn-primary marR10\">新增</button>","<button type=\"button\" id=\"editAccount\" class=\"btn btn-info marR10\">编辑</button>","<button type=\"button\" id=\"delAccount\" class=\"btn btn-danger marR10\">删除</button>"};
        model.addAttribute("res", findByRes());
        model.addAttribute("btn",btnArray);
        return Common.BACKGROUND_PATH + "/device/fault/faultlist";
    }

    @ResponseBody
    @RequestMapping("fault_findByPage")
    public PageInfo findByPage(String pageNow,
                               String pageSize, HttpServletRequest request) throws Exception {
        if(pageNow == null){
            PageHelper.startPage(1, 10);
        }else {
            PageHelper.startPage(Integer.parseInt(pageNow), 10);
        }
        String name =  getPara("deviceName");

        System.out.println("name:.." + name);
        if(name==null || name.equals("")){
            List<DeviceFaultFormMap> deviceFaultFormMaps=deviceMapper.getDeviceFault();
//            //添加查看设备明细按钮
//            for(int i = 0;i < deviceFaultFormMaps.size();i++){
//                DeviceFaultFormMap deviceFaultFormMap = deviceFaultFormMaps.get(i);
//                deviceFaultFormMap.set("detailInfo","<a  id=\"detailInfo\" >查看明细</a>");
//            }

            if(deviceFaultFormMaps.size() > 0){
                PageInfo pageInfo = new PageInfo<>(deviceFaultFormMaps);
                return pageInfo;
            }
            return null;
        }else {
            List<DeviceFaultFormMap> deviceFaultFormMaps=deviceMapper.getDeviceFaultByName(name);
            PageInfo pageInfo = new PageInfo<>(deviceFaultFormMaps);
            return pageInfo;
        }

    }


    @RequestMapping("devicefault_addUI")
    public String addUI(Model model) throws Exception {
        int deviceFaultId = Integer.parseInt(deviceMapper.getDeviceFault().get(deviceMapper.getDeviceFault().size() - 1).get("deviceFaultId").toString());
        model.addAttribute("id", deviceFaultId+1+"A");
        model.addAttribute("deviceFaultId", deviceFaultId+1);
        return Common.BACKGROUND_PATH + "/device/fault/fault_add";
    }

    @RequestMapping("facility")
    public String getFacility(Model model){
        model.addAttribute("data", deviceMapper.getDeviceType());
        return Common.BACKGROUND_PATH + "/device/fault/wupin";
    }

    /**修改前的添加
    @ResponseBody
    @RequestMapping("devicefault_addEntity")
//	@Transactional(readOnly=false)//需要事务操作必须加入此注解
    @SystemLog(module="设备故障管理",methods="设备故障新增")//凡需要处理业务逻辑的.都需要记录操作日志
    public String addEntity(HttpServletRequest request) {
        DeviceFaultFormMap deviceFaultFormMap = getFormMap(DeviceFaultFormMap.class);
        //
        deviceFaultFormMap.set("devicecycle",deviceFaultFormMap.get("devicecycle").toString() + deviceFaultFormMap.get("devicecycletype"));
        try {
            userMapper.addEntity(deviceFaultFormMap);//新增后返回新增信息
            String[] itemNoArr = request.getParameterValues("ly_dev_part");
            String[] itemUseNumberArr = request.getParameterValues("ly_dev_describe");
            if(null != itemNoArr ){
                for(int i = 0 ;i<itemNoArr.length;i++){
                    DevOperationFormMap itemBomFormMap = new DevOperationFormMap();
                    itemBomFormMap.put("ly_dev_part", itemNoArr[i]);
                    itemBomFormMap.put("ly_dev_describe", itemUseNumberArr[i]);
                    itemBomFormMap.put("ly_dev_keyid", deviceFaultFormMap.get("devicegl"));
                    baseMapper.addEntity(itemBomFormMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = new JSONObject();
        json.put("result", ConstantController.SUCCESS);
        return json.toString();
    }
    */

    /**
     * 修改后的添加
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("devicefault_addEntity")
//	@Transactional(readOnly=false)//需要事务操作必须加入此注解
    @SystemLog(module="设备故障管理",methods="设备故障新增")//凡需要处理业务逻辑的.都需要记录操作日志
    public String addEntity(HttpServletRequest request) {
        DeviceFaultFormMap deviceFaultFormMap = getFormMap(DeviceFaultFormMap.class);
        System.out.println("deviceFaultFormMap:.."+deviceFaultFormMap);
        //
        deviceFaultFormMap.set("devicecycle",deviceFaultFormMap.get("devicecycle").toString() + deviceFaultFormMap.get("devicecycletype"));

//        //获取随机数生成deviceFaultId
//        String deviceFaultId = SerialNumberUtil.Getnum("df");//设置随机数前缀获取deviceFaultId
//        deviceFaultFormMap.put("deviceFaultId",deviceFaultId);

        System.out.println("deviceFaultFormMap..."+deviceFaultFormMap.get("deviceFaultId"));

        try {
            userMapper.addEntity(deviceFaultFormMap);//新增后返回新增信息

            //获取添加的panel下标
            String panelNum = request.getParameter("panelNum");

            System.out.println("panelNum:.."+panelNum);
            //分隔字符串panelNum获取下标数组
            String[] panelArr = panelNum.split(",");
            if(panelArr.length > 0){
                for (String panel : panelArr) {//遍历panel获取设备关联的保养部位
                    //获取设备ID和名称
                    String deviceCode = request.getParameter("deviceId"+panel);
                    String deviceName = request.getParameter("deviceName"+panel);
                    System.out.println("---id+name = " + deviceCode + deviceName);
                    //获取设备关联部位下标
                    String partNum = request.getParameter("partSn"+panel);
                    //分隔字符串partNum获取下标数组
                    String[] partArr = partNum.split(",");

                    if(partArr.length > 0){
                        for (String part : partArr) {//遍历part获取保养部位并放入明细表中
    //                        System.out.println("ly_dev_part"+panel+part);
                            String partNameArr = request.getParameter("ly_dev_part"+part);
                            String describeArr = request.getParameter("ly_dev_describe"+part);
                            System.out.println("partNameArr..describeArr"+partNameArr+describeArr);
                            //将获取的数据放入到明细表中
                            DeviceFaultDetailMap deviceFaultDetailMap = getFormMap(DeviceFaultDetailMap.class);
                            deviceFaultDetailMap.set("devicefaultId",deviceFaultFormMap.getStr("deviceFaultId"));
                            deviceFaultDetailMap.set("devicefaultName",deviceFaultFormMap.getStr("devicepan"));
                            deviceFaultDetailMap.set("deviceCode",deviceCode);
                            deviceFaultDetailMap.set("deviceName",deviceName);
                            deviceFaultDetailMap.set("devMaintenancePartName",partNameArr);
                            deviceFaultDetailMap.set("descs",describeArr);
                            baseMapper.addEntity(deviceFaultDetailMap);
                        }
                    }


                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject json = new JSONObject();
        json.put("result", ConstantController.SUCCESS);
        return json.toString();
    }


    /**修改之前的跳转到修改页
    @RequestMapping("devicefault_editUI")
    public String editUI(Model model){
        String id=getPara("id");
        if(Common.isNotEmpty(id)){
            DeviceFaultFormMap deviceFaultId = userMapper.findbyFrist("deviceFaultId", id, DeviceFaultFormMap.class);
            model.addAttribute("bom", deviceMapper.getdo(deviceFaultId.get("devicegl").toString()));
            model.addAttribute("user",userMapper.findbyFrist("deviceFaultId", id, DeviceFaultFormMap.class));
        }
        return Common.BACKGROUND_PATH+"/device/fault/faultedit";
    }
    */

    /**
     * 修改之后跳转到修改页
     * @param model
     * @return
     */
    @RequestMapping("devicefault_editUI")
    public String editUI(Model model){
        String id=getPara("id");//deviceFaultId

        if(Common.isNotEmpty(id)){
            DeviceFaultFormMap deviceFaultFormMap = userMapper.findbyFrist("deviceFaultId", id, DeviceFaultFormMap.class);//获取保养主信息
            model.addAttribute("user",deviceFaultFormMap);

            //根据id获取关联的保养部位信息
            List<DeviceFaultDetailMap> listDetail = deviceMapper.getFaultDetailById(id);

            //前台需要传入的数据有设备id列表、设备名称列表、需要写入的panel下标，设备关联的部位下标（遍历时将其写入到listDetail即可）

            //用与统计panel的下标，例如tb1的1，生成panel时放入，删除panel时取出
            List panelArr = new ArrayList();

            //用与统计deviceId以便于前台去重，例如添加过的设备就无需再添加了
            List deviceIdArr = new ArrayList();

            //用于存放设备名称，用于显示
            List deviceNameArr = new ArrayList();



            int panelNum = 0;//panel初始序数

            String code = "";//用于比较设备是否相同

            // 用于记录设备关联的部位下标
            List partList = new ArrayList();

            List<List<DeviceFaultDetailMap>> DeviceFaultDetailList = new ArrayList<List<DeviceFaultDetailMap>>();

            //遍历结果获取设备个数和列表
            for(int i = 0; i < listDetail.size(); i++){
                DeviceFaultDetailMap deviceFaultDetailMap = listDetail.get(i);
                String deviceCode = deviceFaultDetailMap.getStr("deviceCode");//设备代码
                String deviceName = deviceFaultDetailMap.getStr("deviceName");//设备名称

                if(!code.equals(deviceCode)) {//设备代码不同则是不同设备
                    code = deviceCode;
                    deviceIdArr.add(deviceCode);
                    deviceNameArr.add(deviceName);

                    panelArr.add(panelNum);//放入序数
                    panelNum++;
                }
            }

            for(int i = 0; i < deviceIdArr.size(); i++){
                int partNum = 0;//下标初始序数
                // 用于记录设备关联的部位下标
                List partArr = new ArrayList();

                List<DeviceFaultDetailMap> DeviceFaultArr = new ArrayList<DeviceFaultDetailMap>();

                for(int j = 0; j < listDetail.size(); j++){
                    if(deviceIdArr.get(i).equals(listDetail.get(j).getStr("deviceCode"))){
                        DeviceFaultArr.add(listDetail.get(j));
                        partArr.add(""+i+partNum);
                        partNum++;
                    }

                }
                DeviceFaultDetailList.add(DeviceFaultArr);

                //list转字符串
                String partStr = "";
                for(int k = 0;k<partArr.size();k++){
                    if("".equals(partStr)){
                        partStr += "" + partArr.get(k);
                    }else {
                        partStr += ","+partArr.get(k);
                    }
                }
                partList.add(partStr);
            }



            System.out.println("deviceIdArr"+deviceIdArr);
            System.out.println("deviceNameArr"+deviceNameArr);
            System.out.println("panelArr"+panelArr);
            System.out.println("partList"+partList);
            System.out.println("DeviceFaultDetailList"+DeviceFaultDetailList);


            //将panelArr转为字符串
            String panelStr = "";
            for(int i = 0;i<panelArr.size();i++){
                if("".equals(panelStr)){
                    panelStr += "" + panelArr.get(i);
                }else {
                    panelStr += ","+panelArr.get(i);
                }
            }

            model.addAttribute("listDetail",listDetail);
            model.addAttribute("deviceIdArr",deviceIdArr);
            model.addAttribute("deviceNameArr",deviceNameArr);

            model.addAttribute("panelArr",panelArr);
            model.addAttribute("panelStr",panelStr);

            model.addAttribute("partList",partList);
            model.addAttribute("DeviceFaultDetailList",DeviceFaultDetailList);

        }

        return Common.BACKGROUND_PATH+"/device/fault/faultedit";
    }

    /**修改前的数据修改
    @ResponseBody
    @RequestMapping("devicefault_editEntity")
    @SystemLog(module="设备故障管理",methods="设备故障编辑")//凡需要处理业务逻辑的.都需要记录操作日志
    public String editEntity(HttpServletRequest request) throws Exception {

        DeviceFaultFormMap deviceFaultFormMap = getFormMap(DeviceFaultFormMap.class);
        userMapper.deleteByAttribute("deviceFaultId", deviceFaultFormMap.get("deviceFaultId")+"", DeviceFaultFormMap.class);
        userMapper.addEntity(deviceFaultFormMap);
        //删除关联子类
        deviceMapper.deleteByAttribute("ly_dev_keyid","'"+deviceFaultFormMap.get("devicegl").toString()+"'",DevOperationFormMap.class);

        String[] itemNoArr = request.getParameterValues("ly_dev_part");
        String[] itemUseNumberArr = request.getParameterValues("ly_dev_describe");
        if(null != itemNoArr ){
            for(int i = 0 ;i<itemNoArr.length;i++){
                DevOperationFormMap itemBomFormMap = new DevOperationFormMap();
                itemBomFormMap.put("ly_dev_part", itemNoArr[i]);
                itemBomFormMap.put("ly_dev_describe", itemUseNumberArr[i]);
                itemBomFormMap.put("ly_dev_keyid", deviceFaultFormMap.get("devicegl"));
                baseMapper.addEntity(itemBomFormMap);
            }
        }

        JSONObject json = new JSONObject();
        json.put("result", ConstantController.SUCCESS);
        return json.toString();
    }
    */

    /**
     * 修改后的数据修改
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("devicefault_editEntity")
    @SystemLog(module="设备故障管理",methods="设备故障编辑")//凡需要处理业务逻辑的.都需要记录操作日志
    public String editEntity(HttpServletRequest request) throws Exception {

        DeviceFaultFormMap deviceFaultFormMap = getFormMap(DeviceFaultFormMap.class);
        userMapper.deleteByAttribute("deviceFaultId", deviceFaultFormMap.get("deviceFaultId")+"", DeviceFaultFormMap.class);
        userMapper.addEntity(deviceFaultFormMap);
        //根据id获取关联的保养部位信息
        deviceMapper.deleteByAttribute("devicefaultId",deviceFaultFormMap.getStr("deviceFaultId")+"",DeviceFaultDetailMap.class);
        //获取添加的panel下标
        String panelNum = request.getParameter("panelNum");

        System.out.println("panelNum:.."+panelNum);
        //分隔字符串panelNum获取下标数组
        String[] panelArr = panelNum.split(",");
        if(panelArr.length > 0){
            for (String panel : panelArr) {//遍历panel获取设备关联的保养部位
                //获取设备ID和名称
                String deviceCode = request.getParameter("deviceId"+panel);
                String deviceName = request.getParameter("deviceName"+panel);
                System.out.println("---id+name = " + deviceCode + deviceName);
                //获取设备关联部位下标
                String partNum = request.getParameter("partSn"+panel);
                //分隔字符串partNum获取下标数组
                String[] partArr = partNum.split(",");

                if(partArr.length > 0){
                    for (String part : partArr) {//遍历part获取保养部位并放入明细表中
                        //                        System.out.println("ly_dev_part"+panel+part);
                        String partNameArr = request.getParameter("ly_dev_part"+part);
                        String describeArr = request.getParameter("ly_dev_describe"+part);
                        System.out.println("partNameArr..describeArr"+partNameArr+describeArr);
                        //将获取的数据放入到明细表中
                        DeviceFaultDetailMap deviceFaultDetailMap = getFormMap(DeviceFaultDetailMap.class);
                        deviceFaultDetailMap.set("devicefaultId",deviceFaultFormMap.getStr("deviceFaultId"));
                        deviceFaultDetailMap.set("devicefaultName",deviceFaultFormMap.getStr("devicepan"));
                        deviceFaultDetailMap.set("deviceCode",deviceCode);
                        deviceFaultDetailMap.set("deviceName",deviceName);
                        deviceFaultDetailMap.set("devMaintenancePartName",partNameArr);
                        deviceFaultDetailMap.set("descs",describeArr);
                        baseMapper.addEntity(deviceFaultDetailMap);
                    }
                }


            }
        }

        JSONObject json = new JSONObject();
        json.put("result", ConstantController.SUCCESS);
        return json.toString();
    }



    @ResponseBody
    @RequestMapping("devicefault_deleteEntity")
    @Transactional(readOnly=false)//需要事务操作必须加入此注解
    @SystemLog(module="设备故障管理",methods="删除设备故障")//凡需要处理业务逻辑的.都需要记录操作日志
    public String deleteEntity() throws Exception {
        String[] ids = getParaValues("ids");
        for (String id : ids) {
            baseMapper.deleteByAttribute("deviceFaultId", id, DeviceFaultFormMap.class);
            baseMapper.deleteByAttribute("deviceFaultId", id, DeviceFaultDetailMap.class);
        }
        return "success";
    }

    /**
     * 弹出设备明细页面
     * @param model
     * @return
     */
    @RequestMapping("deviceDetail")
    public String deviceDetail(Model model){
        //获取相关的项目信息然之后分割字符串之后根据检验内容进行查询

        String devicefaultId = getPara("id");

        //根据id获取数据
        List<DeviceFaultDetailMap> listDetail = deviceMapper.getFaultDetailById(devicefaultId);
        System.out.println("listDetail:.."+listDetail);
//        //获取数据
//        String name = ma.get(0).get("detection_pproduct").toString();
//        //分割字符串
//        String[] split = name.split(",");
//        List<ProjectJcForMmap>  pjList = new ArrayList<>();
//        if(split.length > 0){
//            for (String n : split) {
//                List<ProjectJcForMmap> content = projuctJcMapper.getContent(n);
//                pjList.add(content.get(0));
//            }
//        }
        model.addAttribute("list",listDetail);
        return Common.BACKGROUND_PATH + "/device/fault/deviceDetailInfo";
    }

    /**
     * 获取所有设备信息
     */
    @RequestMapping("getDeviceInfo")
    public String getDeviceInfo(Model model){
        List<DeviceFormMap> listDetail = deviceMapper.getDeviceInfo();//查所有传入空串
        model.addAttribute("data", listDetail);
        return Common.BACKGROUND_PATH + "/device/fault/wupin";
    }


    /**
     * 根据名称获取设备信息
     */
    @ResponseBody
    @RequestMapping("getDeviceInfoByName")
    public Object getDeviceInfoByName(HttpServletRequest req){
        String name = req.getParameter("name");
        List<DeviceFormMap> listDetail = deviceMapper.getDeviceInfoByName(name);
        return listDetail;
    }


    /**
     * 根据设备类型id获取设备关联部位信息
     */
    @ResponseBody
    @RequestMapping("getDeviceParts")
    public Object getDeviceParts(Model model){

        String deviceTypeId = getPara("id");

        //获取设备关联的部位
        List<DevicePartsMap> ListParts = deviceMapper.getPartsByTypeId(deviceTypeId);

        //将保养部位id根据逗号拆分
        //分割字符串
        return ListParts;
    }


}
